package reign.network.host;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
import java.util.logging.Logger;

import reign.network.user.NetworkUser;
import reign.network.user.User;
import reign.network.user.User.userType;

public class UserListener extends Thread{
	
	ServerSocket listener;
	private Logger logger;
	Session thisSession;
	
	public static void main(String [] args)
	{
		UserListener temp = new UserListener("Game1",8090);
		temp.startListening();
	}
	
	public UserListener(String name,int port)
	{
		logger = Logger.getLogger("UserListener");
		 try {
			listener = new ServerSocket(port);
		} catch (IOException e) {
			logger.severe("Unable to open ServerSocket on port:" + port);
		}
		thisSession = new Session(UUID.randomUUID(),name);
	}
	
	public boolean startListening()
	{
		this.start();
		return this.isAlive();
	}
	
	public Session getSession()
	{
	  return thisSession;	
	}

	@Override
	public void run() {
		
		while(!thisSession.isLocked())
		{
			Socket incoming = null;
			try {
				incoming = listener.accept();
			    ObjectInputStream ois = new ObjectInputStream(incoming.getInputStream());
			    // read the objects from the input stream (the file name.out)
			    User userData = (User) ois.readObject();
			    userData = new NetworkUser(userData.getIdNumber(),userData.getUsername(),userData.getProvidedPassword(),userType.NETWORK_USER,incoming);
			    thisSession.addUser(userData);
			    System.out.println("Adding to Session " + thisSession.getName() + "- Username: " + userData.getUsername() + " Pass: " + userData.getProvidedPassword() + " UUID: " + userData.getIdNumber().toString());
			} catch (IOException e) {
				logger.severe("Unable to Catch user socket");
			} catch (ClassNotFoundException e) {
				logger.severe("User didn't respond with a user Class");
				if(incoming != null)
					{
					 try {
						incoming.close();
					} catch (IOException e1) {
						logger.warning("Unable to close incoming connection");
					}
					}
			}
		}
	}

}
